package com.study.util;

import com.study.dao.UserDao;
import com.study.service.UserService;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author chenyeqing
 * @Date 2021/9/13 20:51
 */
public class BeanFactory {

    private static Properties env = new Properties();
    private static InputStream inputStream = null;

    static {
        try {
            inputStream = BeanFactory.class.getResourceAsStream("/applicationContext.properties");
            env.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建一个对象的方式有几种
     * 1、 直接 new
     * 2、 通过反射
     *
     * @return
     */
    public static UserService getUserService() {
        // 同样的，如果有一个新的实现类，这里也需要修改，不符合开闭原则
        // return new UserServiceImpl();
        UserService userService = null;
        try {
            Class clazz = Class.forName(env.getProperty("userService"));
            userService = (UserService) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return userService;
    }

    public static UserDao getUserDao() {
        UserDao userDao = null;
        try {
            Class userClazz = Class.forName(env.getProperty("userDao"));
            userDao = (UserDao) userClazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return userDao;
    }

    /**
     * 通用工厂
     * @param key
     * @return
     */
    public static Object getBean(String key) {
        Object obj = null;
        try {
            Class userClazz = Class.forName(env.getProperty(key));
            obj = userClazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
